package com.mzj.saas.jobs.ad.service;


import com.mzj.saas.jobs.ad.vo.AdvTaskVO;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 根据广告有效期、上架状态、审核状态，查询符合的广告,缓存到redis
 */

@Service
public class  AdService {
    private static Logger log = LoggerFactory.getLogger(AdService.class);

    private static final String SAAS_ADVERTISMENT = "saas:advertisement:%s";

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    @Qualifier("redisTemplate")
    private StringRedisTemplate redisTemplate;

    public String work() throws Exception {

        //同步redis
        syncAdvSpaceToRedis();

        return "SUCCESS";
    }

    /**
     * 同步redis
     */
  /*  public void syncAdvSpaceToRedis() {
        try {

            String sql = "SELECT\n" +
                    "  s.code,\n" +
                    "  a.ad_pic,\n" +
                    "  a.ad_link,\n" +
                    "  a.name,\n" +
                    "  a.content\n" +
                    "FROM\n" +
                    "  saas_ad a\n" +
                    "  LEFT JOIN saas_ad_space s\n" +
                    "    ON s.id = a.space_id\n" +
                    "WHERE a.`auditor_status` = 1\n" +
                    "  AND a.`status` = 1\n" +
                    "  AND a.`expire`>=NOW()";

            List<AdvTaskVO> advTaskVos = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(AdvTaskVO.class));
            Map<String, List<AdvTaskVO>> collect = advTaskVos.stream().collect(Collectors.groupingBy(AdvTaskVO::getCode));
            Set<String> set = collect.keySet();

            collect.forEach((code, vos) -> {
                JSONArray jsonObject = JSONArray.fromObject(vos.toArray());
                redisTemplate.opsForValue().set(String.format(SAAS_ADVERTISMENT, code), jsonObject.toString(), 15, TimeUnit.MINUTES);
            });
//            for (String code:set) {
//                List<AdvTaskVO> list = collect.get(code);
//                for (int i = 0; i < list.size(); i++) {
//
//
//                }
//                stringRedisTemplate.opsForValue().set(String.format(SAAS_ADVERTISMENT,code),
//                        JSONUtils.toJSONString("123"),15, TimeUnit.MINUTES);
//            }


        } catch (Exception e) {
            log.error("AdvertisementScheduledTasks AdvertisementTask Exception = {}", e.getMessage());
        }

    }*/
    public void syncAdvSpaceToRedis() {
        try {

            //先删除redis中的数据
            String sql1 = "SELECT code FROM saas_ad_space";
            List<AdvTaskVO> adSpaceVos = jdbcTemplate.query(sql1, new BeanPropertyRowMapper<>(AdvTaskVO.class));
            adSpaceVos.forEach((code) -> {
                redisTemplate.delete(String.format(SAAS_ADVERTISMENT, code.getCode()));
            });

            String sql = "SELECT\n" +
                    "  s.code,\n" +
                    "  a.ad_pic,\n" +
                    "  a.ad_link,\n" +
                    "  a.name,\n" +
                    "  a.content\n" +
                    "FROM\n" +
                    "  saas_ad a\n" +
                    "  LEFT JOIN saas_ad_space s\n" +
                    "    ON s.id = a.space_id\n" +
                    "WHERE a.`auditor_status` = 1\n" +
                    "  AND a.`status` = 1\n" +
                    "  AND a.`expire`>=NOW()";

            List<AdvTaskVO> advTaskVos = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(AdvTaskVO.class));
            Map<String, List<AdvTaskVO>> collect = advTaskVos.stream().collect(Collectors.groupingBy(AdvTaskVO::getCode));
            Set<String> set = collect.keySet();
            collect.forEach((code, vos) -> {
                JSONArray jsonObject = JSONArray.fromObject(vos.toArray());
                redisTemplate.opsForValue().set(String.format(SAAS_ADVERTISMENT, code), jsonObject.toString(), 43200, TimeUnit.MINUTES);
            });


        } catch (Exception e) {
            log.error("AdvertisementScheduledTasks AdvertisementTask Exception = {}", e.getMessage());
        }

    }

}
